package com.erongdu.utils;

import java.net.*;
import java.util.Enumeration;

/**
 * Created by syq on 2015/10/29.
 */
public class Ipaddr {


    public static String ipv4() {
        Enumeration allNetInterfaces = null;
        InetAddress ip = null;
//        List<String> list = new ArrayList<String>();
        String ipv4s = "";
        try {
            allNetInterfaces = NetworkInterface.getNetworkInterfaces();
            while (allNetInterfaces.hasMoreElements()) {
                NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
//                System.out.println(netInterface.getName());
                Enumeration addresses = netInterface.getInetAddresses();
                while (addresses.hasMoreElements()) {
                    ip = (InetAddress) addresses.nextElement();
                    if (ip != null && ip instanceof Inet4Address) {
                        ipv4s += ip.getHostAddress()+",";
//                        list.add(ip.getHostAddress());
//                        System.out.println("本机的IP = " + ip.getHostAddress());
                    }
                }
            }
            if (!ipv4s.isEmpty()){
                ipv4s = ipv4s.substring(0,ipv4s.length()-1);
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return ipv4s;
    }



    /**
     * 获取本机所有物理地址
     *
     * @return
     */
    public static String getMacAddress() {
        NetworkInterface netInterface = null;
        String mac = "";
        try {
            netInterface = NetworkInterface.getByInetAddress(InetAddress.getLocalHost());
            // 获得Mac地址的byte数组
            byte[] macAddr = netInterface.getHardwareAddress();
//            System.out.print("MAC Addr:\t");
            // 循环输出
            for (byte b : macAddr) {
                // 这里的toHexString()是自己写的格式化输出的方法，见下步。
                mac += toHexString(b) + " ";
            }
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return mac;
    }

    private static String toHexString(int integer) {
        // 将得来的int类型数字转化为十六进制数
        String str = Integer.toHexString((int) (integer & 0xff));
        // 如果遇到单字符，前置0占位补满两格
        if (str.length() == 1) {
            str = "0" + str;
        }
        return str;
    }


}
